package io.demo.petstore.web;


import io.demo.petstore.account.Account;
import io.demo.petstore.account.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

/**
 * User register controller
 *
 * @author lijinting01
 */
@RestController
@RequestMapping("/account/register")
public class RegisterController {

  private final AccountService accountService;

  public RegisterController(@Autowired AccountService accountService) {
    this.accountService = accountService;
  }


  @PostMapping
  @ResponseStatus(HttpStatus.CREATED)
  public Account register(@RequestBody RegisterRequest account) {
    if (account == null) {
      throw new IllegalArgumentException();
    }

    return accountService.register(account.toEntity());
  }
}

@Controller
@RequestMapping("/account/register")
class RegisterView {

  @GetMapping
  public String view(Model model) {
    model.addAttribute("title", "Register Your Account");
    return "/account/register";
  }
}

class RegisterRequest extends Account {

  Account toEntity() {
    return Account.builder()
        .password(this.getPassword())
        .username(this.getUsername())
        .customer(this.getCustomer())
        .build();
  }
}